﻿#include "salequerywidget.h"
#include "ui_salequerywidget.h"

SaleQueryWidget::SaleQueryWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SaleQueryWidget)
{
    ui->setupUi(this);

    relation = nullptr;
    product = nullptr;

    ui->comboBoxTicket->setCurrentIndex(2);
    ui->comboBoxMoney->setCurrentIndex(2);

    ui->tableView->setModel(&model);
    ui->tableView->setMultiListPushButton(ui->pushButtonList);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSortingEnabled(true);

    ui->dateEditStartTime->setDisplayFormat("yyyy-MM-dd");
    ui->dateEditStartTime->setMinimumDate(Tools::getBaseDate());
    ui->dateEditStartTime->setMaximumDate(QDate::currentDate());

    ui->dateEditEndTime->setDisplayFormat("yyyy-MM-dd");
    ui->dateEditEndTime->setMinimumDate(Tools::getBaseDate());
    ui->dateEditEndTime->setMaximumDate(QDate::currentDate());
    ui->dateEditEndTime->setDate(QDate::currentDate());

    lastStartDate = Tools::getBaseDate();
    lastEndDate = QDate::currentDate();

    connect(&model, &SaleQueryStandardItemModel::updateTotalProfit,
            [=](double totalProfit, double averageProfit)
    {
        ui->labelTotalProfit->setText("毛利润合计："+QString::number(totalProfit, 'f', 2));
        ui->labelAverageProfit->setText("平均毛利率："+QString::number(averageProfit, 'f', 2)+"%");
    });

    connect(&model, &SaleQueryStandardItemModel::updateTotalValue,
            [=](double totalValue, double totalTicket, double totalMoney)
    {
        ui->labelTotalValue->setText("金额："+QString::number(totalValue, 'f', 2));
        if(widgetType == UserRelation::Client){
            ui->labelTotalTicket->setText("应开发票："+QString::number(totalTicket, 'f', 2));
            ui->labelTotalMoney->setText("应收货款："+QString::number(totalMoney, 'f', 2));
        }else{
            ui->labelTotalTicket->setText("应收发票："+QString::number(totalTicket, 'f', 2));
            ui->labelTotalMoney->setText("应付货款："+QString::number(totalMoney, 'f', 2));
        }
    });

    connect(&userPicker, &UserPicker::selectedFinished,
            [=](UserRelation *relation)
    {
        this->relation = relation;
        ui->lineEditClientName->setText(relation->nickName);
        ui->lineEditContact->setText(relation->contact);
        ui->lineEditTel->setText(relation->tel);
    });

    productPicker.setSelectionMode(QAbstractItemView::SingleSelection);

    connect(ui->lineEditClientName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        userPicker.loadData();
        userPicker.exec();
    });

    connect(ui->lineEditContact, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        userPicker.loadData();
        userPicker.exec();
    });

    connect(ui->lineEditTel, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        userPicker.loadData();
        userPicker.exec();
    });

    connect(&productPicker, &ProductPicker::singleSelected,
            [=](Product *product, int defaultCount)
    {
        Q_UNUSED(defaultCount);
        this->product = product;
        ui->lineEditProductName->setText(product->name);
        ui->lineEditProductType->setText(product->type);
    });

    connect(ui->lineEditProductName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(ui->lineEditProductType, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(&dingdanService, &DingdanService::queryDingdanSuccess,
            [=](QList<Dingdan*> dingdans)
    {
        this->dingdans = dingdans;
        model.setType(0);
        model.reset();
        ui->tableView->refreshMultiHiddenState();
        model.insertDingdan(dingdans);
    });

    connect(&dingdanService, &DingdanService::queryDingdanDetailSuccess,
            [=](QList<DingdanAndDetail*> details)
    {
        this->details = details;
        model.setType(1);
        model.reset();
        ui->tableView->refreshMultiHiddenState();
        model.insertDingdanDetail(details);
    });

    connect(ui->tableView, &QTableView::doubleClicked,
            [=](QModelIndex index)
    {
        qDebug()<<index.row();
        if(index.isValid()){
            QString dingdanId = model.getDingdanId(index.row());
            if(dingdanId!=nullptr){
                dingdanDetailWidget.showWithDingdanId(dingdanId);
            }
        }
    });
}

SaleQueryWidget::~SaleQueryWidget()
{
    delete ui;
}

void SaleQueryWidget::setWidgetType(SaleQueryStandardItemModel::WidgetType widgetType){
    model.setWidgetType(widgetType);

    if(widgetType == SaleQueryStandardItemModel::Sale){
        this->widgetType = UserRelation::Client;
        ui->labelTypeName->setText("销售查询");
        ui->labelType->setText("客户名称");
        ui->labelTotalTicket->setText("应开发票：0.00");
        ui->labelTotalMoney->setText("应收货款：0.00");
        type = 0;
        ui->tableView->addMultiMenu("salequery/client_dingdan", model.headerDingdan);
        ui->tableView->addMultiMenu("salequery/client_detail", model.headerDetail);
    }else if(widgetType == SaleQueryStandardItemModel::Purchase){
        this->widgetType = UserRelation::Giver;
        ui->labelTypeName->setText("采购查询");
        ui->labelType->setText("供应商名称");
        ui->labelTotalTicket->setText("应收发票：0.00");
        ui->labelTotalMoney->setText("应付货款：0.00");
        ui->tableView->addMultiMenu("salequery/giver_dingdan", model.headerDingdan);
        ui->tableView->addMultiMenu("salequery/giver_detail", model.headerDetail);
        type = 1;
    }else{
        this->widgetType = UserRelation::Client;
        ui->labelTypeName->setText("利润查询");
        ui->labelType->setText("客户名称");
        type = 0;
        ui->tableView->addMultiMenu("salequery/profit_dingdan", model.headerDingdan);
        ui->tableView->addMultiMenu("salequery/profit_detail", model.headerDetail);
    }

    ui->widgetProfit->setVisible(widgetType == SaleQueryStandardItemModel::Profit);
    ui->widgetTotal->setVisible(widgetType != SaleQueryStandardItemModel::Profit);
    userPicker.setWidgetType(this->widgetType);
    ui->tableView->initMultiHiddenStateList();
    ui->tableView->refreshMultiHiddenState();
    ui->comboBoxQueryType->setCurrentIndex(1);
}

void SaleQueryWidget::on_comboBoxQueryType_currentIndexChanged(int index)
{
    model.setType(index);
    model.reset();
    ui->pushButtonList->setCurrentMenuIndex(index);
    ui->tableView->refreshMultiHiddenState();
}

void SaleQueryWidget::on_pushButtonClear_clicked()
{
    this->relation = nullptr;
    this->product = nullptr;

    ui->lineEditClientName->clear();
    ui->lineEditContact->clear();
    ui->lineEditTel->clear();

    ui->lineEditProductName->clear();
    ui->lineEditProductType->clear();

    ui->comboBoxQueryType->setCurrentIndex(0);
    ui->dateEditEndTime->setTime(QTime::currentTime());

    model.reset();
}

void SaleQueryWidget::on_pushButtonQuery_clicked()
{
    int queryType = ui->comboBoxQueryType->currentIndex();
    this->dingdans.clear();
    this->details.clear();
    ui->comboBoxTicket->setCurrentIndex(0);
    ui->comboBoxMoney->setCurrentIndex(0);

    QString targetUsername;
    QString productId;
    targetUsername = relation==nullptr?"":relation->targetUsername;
    productId = product==nullptr?"":product->productId;

    if(queryType == 0){
        //按单号查询
        dingdanService.queryDingdan(
                    this,
                    type,
                    targetUsername,
                    ui->dateEditStartTime->text(),
                    ui->dateEditEndTime->text());
    }else{
        //按明细查询
        dingdanService.queryDingdanDetail(
                    this,
                    type,
                    targetUsername,
                    productId,
                    ui->dateEditStartTime->text(),
                    ui->dateEditEndTime->text());
    }
}

void SaleQueryWidget::on_comboBoxTicket_currentIndexChanged(int index)
{
    int queryType = ui->comboBoxQueryType->currentIndex();
    model.setType(queryType);
    model.reset();
    if(queryType == 0){
        QList<Dingdan*> resultDingdan = dingdanService.queryDingdan(
                    dingdans,
                    widgetType,
                    index,
                    ui->comboBoxMoney->currentIndex());
        model.insertDingdan(resultDingdan);
    }else{
        QList<DingdanAndDetail*> resultDetail = dingdanService.queryDingdanDetail(
                    details,
                    widgetType,
                    index,
                    ui->comboBoxMoney->currentIndex());
        model.insertDingdanDetail(resultDetail);
    }
}

void SaleQueryWidget::on_comboBoxMoney_currentIndexChanged(int index)
{
    int queryType = ui->comboBoxQueryType->currentIndex();
    model.setType(queryType);
    model.reset();
    if(queryType == 0){
        QList<Dingdan*> resultDingdan = dingdanService.queryDingdan(
                    dingdans,
                    widgetType,
                    ui->comboBoxTicket->currentIndex(),
                    index);
        model.insertDingdan(resultDingdan);
    }else{
        QList<DingdanAndDetail*> resultDetail = dingdanService.queryDingdanDetail(
                    details,
                    widgetType,
                    ui->comboBoxTicket->currentIndex(),
                    index);
        model.insertDingdanDetail(resultDetail);
    }
}

void SaleQueryWidget::on_dateEditStartTime_dateChanged(const QDate &date)
{
    QDate endDate = ui->dateEditEndTime->date();

    if(date > endDate){
        ui->dateEditStartTime->setDate(lastStartDate);
    }else{
        lastStartDate = date;
        ui->dateEditStartTime->setDate(date);
    }
}

void SaleQueryWidget::on_dateEditEndTime_dateChanged(const QDate &date)
{
    QDate startDate = ui->dateEditStartTime->date();

    if(date < startDate){
        ui->dateEditEndTime->setDate(lastEndDate);
    }else{
        lastEndDate = date;
        ui->dateEditEndTime->setDate(date);
    }
}

void SaleQueryWidget::on_pushButtonDetail_clicked()
{
    QModelIndex index = ui->tableView->currentIndex();
    if(index.isValid()){
        QString dingdanId = model.getDingdanId(index.row());
        if(dingdanId!=nullptr){
            dingdanDetailWidget.showWithDingdanId(dingdanId);
        }
    }else{
        QMessageBox::warning(this, "警告", "请选择订单信息！");
    }
}
